package de.hci.mid.socialmap.beans;

import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

import de.hci.mid.socialmap.datamanagement.MysqlConnector;
import de.hci.mid.socialmap.entities.Event;
import de.hci.mid.socialmap.entities.ImageHolder;

/**
 * @author Dome
 *
 */
@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private boolean isLoggedIn;

	private String password;
	private String username;

	private int id;

	private final static String[] typs;
	private SelectItem[] typOptions;
	private Event[] selectedEvents;
	EntityManagerFactory emf;

	static {
		typs = new String[6];
		typs[0] = "Party";
		typs[1] = "Schnäppchen";
		typs[2] = "Vorlesung";
		typs[3] = "Sport";
		typs[4] = "Shoutout";
		typs[5] = "Kultur";
	}

	private MysqlConnector conn = null;

	private String getEvents = "SELECT s FROM Event s";

	private List<Event> events;
	private List<Event> filteredEvents;

	public LoginBean() throws ClassNotFoundException, SQLException {
		typOptions = createFilterOptions(typs);
		conn = new MysqlConnector();
		emf = Persistence.createEntityManagerFactory("SocialmapServer");
		refreshEvents();
		
	}

	/**
	 * Reload Events
	 * 
	 * 
	 */
	@SuppressWarnings("unchecked")
	public void refreshEvents() {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("SocialmapServer");
		EntityManager em = emf.createEntityManager();
		events = (List<Event>) em.createQuery(getEvents).getResultList();
		em.close();
	}

	/**
	 * Redirects if user is valid
	 * 
	 * @param actionEvent
	 * @throws SQLException
	 */
	public void login(ActionEvent actionEvent) throws SQLException {
		if (conn.checkLogin(username, password)) {
			isLoggedIn = true;
			doRedirect("hauptmenu.xhtml");
		}

		FacesContext context = FacesContext.getCurrentInstance();
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Username oder Password falsch!");
		context.addMessage(null, msg);

	}

	/**
	 * Verifies Userlogin
	 * 
	 * @param event
	 */
	public void verifyUseLogin(ComponentSystemEvent event) {
		System.out.println("User is logged in: " + isLoggedIn);
		if (!isLoggedIn) {
			doRedirect("login.xhtml");
		}
	}

	/**
	 * Redirect to given URL
	 * 
	 * @param url
	 */
	public void doRedirect(String url) {
		try {
			FacesContext context = FacesContext.getCurrentInstance();
			context.getExternalContext().redirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Delete selected Database Entry
	 * 
	 * @param e
	 */
	public void deleteSelected(ActionEvent e) {

		if (selectedEvents.length == 0) {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "System Error", "Please selected Events to delete!");
			FacesContext.getCurrentInstance().addMessage(null, message);
		} else {
			
			EntityManager em = emf.createEntityManager();
			EntityTransaction tx = em.getTransaction();
			tx.begin();
			for (Event ev : selectedEvents) {
				Event remover = em.find(Event.class, ev.getId());
				ImageHolder removerImage = em.find(ImageHolder.class, ev.getId());
				em.remove(remover);
				em.remove(removerImage);
			}
			em.getTransaction().commit();
			em.close();
			refreshEvents();

		}
	}

	/**
	 * Delete all Database Entries
	 * 
	 * @param e
	 */
	public void deleteAll(ActionEvent e) {
		EntityManager em = emf.createEntityManager();
		EntityTransaction entr=em.getTransaction();
		entr.begin();
		Query q1 = em.createQuery ("DELETE FROM Event s");
		Query q2 = em.createQuery ("DELETE FROM ImageHolder i");
		int dels = q1.executeUpdate();
		q2.executeUpdate();
		entr.commit();
		em.close();
		
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Deleted", ""+dels+" Events deleted!");
		FacesContext.getCurrentInstance().addMessage(null, message);
		refreshEvents();

	}

	/**
	 * @param data
	 * @return
	 */
	private SelectItem[] createFilterOptions(String[] data) {
		SelectItem[] options = new SelectItem[data.length + 1];

		options[0] = new SelectItem("", "Select");
		for (int i = 0; i < data.length; i++) {
			options[i + 1] = new SelectItem(data[i], data[i]);
		}

		return options;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public List<Event> getEvents() {
		return events;
	}

	public void setEvents(List<Event> events) {
		this.events = events;
	}

	public List<Event> getFilteredEvents() {
		return filteredEvents;
	}

	public void setFilteredEvents(List<Event> filteredEvents) {
		this.filteredEvents = filteredEvents;
	}

	public Event[] getSelectedEvents() {
		return selectedEvents;
	}

	public void setSelectedEvents(Event[] selectedEvents) {
		this.selectedEvents = selectedEvents;
	}

	public SelectItem[] getTypOptions() {
		return typOptions;
	}

}
